var _ = require("lodash")

var data = {
    news:"",
    goods:"",
    newsCate:"",
    cateChild:"",
    carts:[],
}

const reducer = (state=data,action={}) => {
    const {type,payload} = action;
    switch(type){
        case "GETNEWS":
            return Object.assign({},state,{news:payload.data,cateChild:payload.ids});
        case "GETGOODS":
            return Object.assign({},state,{goods:payload.data,cateChild:payload.ids});
        case "GETNEWSCATE":
            return Object.assign({},state,{newsCate:payload});
        case "GETCATECHILD":
            return Object.assign({},state,{cateChild:payload});
        case "ADDTOCART":
            var pos = _.findIndex(state.carts,{'_id':payload._id});//匹配
            if(pos == -1){
                payload.quantity = 1;
                return {
                    ...state,
                    carts:[...state.carts,payload]
                };
            }else{
                // var goods = JSON.parse(JSON.stringify(state.carts));
                // goods[pos].quantity = Number(goods[pos].quantity)+1;
                state.carts[pos].quantity += 1;
                return {
                    ...state,
                    carts:state.carts
                };
            }
        case "DOWN":
            var pos = _.findIndex(state.carts,{'_id':payload._id});//匹配
            if(state.carts[pos].quantity>1){
                payload.quantity = state.carts[pos].quantity - 1;
            }
            return {
                ...state,
                carts:[...state.carts,payload]
            };
        case "UP":
            var pos = _.findIndex(state.carts,{'_id':payload._id});//匹配
            payload.quantity = state.carts[pos].quantity + 1;
            return {
                ...state,
                carts:[...state.carts,payload]
            };
        case "DELETE":
            var _id = payload._id;
            var goods = JSON.parse(JSON.stringify(state.carts));
            for(var i=0;i<goods.length;i++){
                if(goods[i]._id == _id){
                    goods.splice(i,1);
                    i--;
                }
            }
            console.log(goods)
            return {
                ...state,
                carts:goods
            };
        default:
            return state;
    }
};

module.exports = reducer;